<template>
  <view class="record-list">
    <view class="section-header">
      <text class="title">往来记录</text>
      <view class="sort-area">
        <view class="sort-hint">
          <text class="sort-hint-icon">↓↑</text>
          <text>排序</text>
        </view>
        <view class="sort-container">
          <view class="sort-item" @tap="toggleSort('name')">
            <text>姓名</text>
            <text class="sort-icon" v-if="sortField === 'name'">
              {{ sortDirection === 'asc' ? '↑' : '↓' }}
            </text>
          </view>
          <view class="sort-item" @tap="toggleSort('type')">
            <text>类型</text>
            <text class="sort-icon" v-if="sortField === 'type'">
              {{ sortDirection === 'asc' ? '↑' : '↓' }}
            </text>
          </view>
          <view class="sort-item" @tap="toggleSort('amount')">
            <text>金额</text>
            <text class="sort-icon" v-if="sortField === 'amount'">
              {{ sortDirection === 'asc' ? '↑' : '↓' }}
            </text>
          </view>
          <view class="sort-item" @tap="toggleSort('time')">
            <text>时间</text>
            <text class="sort-icon" v-if="sortField === 'time'">
              {{ sortDirection === 'asc' ? '↑' : '↓' }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <view class="record-content">
      <scroll-view class="record-scroll-view" scroll-y="true" :show-scrollbar="true">
        <view class="record-items">
          <view 
            v-for="(record, index) in sortedRecords" 
            :key="`record-${record.id}-${index}`"
            class="record-item"
            :class="{ 
              'record-item--receive': record.type === 'receive', 
              'record-item--give': record.type === 'give', 
              'record-item--expanded': expandedRecords[record.id] 
            }"
            @tap="toggleRecordExpand(record.id)"
          >
            <view class="record-header">
              <text class="contact-name">{{ record.contactName || getContactName(record.contactId) }}</text>
              <view class="header-right">
                <text class="amount" :class="{'amount-receive': record.type === 'receive', 'amount-give': record.type === 'give'}">
                  ¥{{ formatAmount(record.amount) }}
                </text>
                <text class="record-type" :class="{'type-receive': record.type === 'receive', 'type-give': record.type === 'give'}">
                  {{ getRecordTypeLabel(record.type) }}
                </text>
                <text class="expand-arrow" :class="{'expanded': expandedRecords[record.id]}">{{ expandedRecords[record.id] ? '↑' : '↓' }}</text>
              </view>
            </view>
            
            <view class="record-details" v-if="expandedRecords[record.id]">
              <view class="details-container" v-if="record.giftName || record.remarks">
                <view class="gift-name" v-if="record.giftName">
                  <text class="gift-icon">🎁</text>
                  <text>{{ record.giftName }}</text>
                </view>
                <view class="remark" v-if="record.remarks">
                  <text class="remark-icon">📝</text>
                  <text>{{ record.remarks }}</text>
                </view>
              </view>
              
              <view class="record-footer">
                <text class="time">{{ formatTime(record.createTime) }}</text>
                <view class="actions">
                  <text class="edit" @tap.stop="handleEditRecord(record)">编辑</text>
                  <text class="delete" @tap.stop="handleDeleteRecord(record)">删除</text>
                </view>
              </view>
            </view>
          </view>
        </view>
  
        <!-- 空状态 -->
        <view v-if="!records || !records.length" class="empty-state">
          <view class="empty-icon">
            <text class="emoji">📝</text>
          </view>
          <text class="empty-title">暂无往来记录</text>
          <text class="empty-desc">点击下方"单笔添加"或"批量添加"按钮来创建记录</text>
        </view>
        
        <!-- 底部安全区域 -->
        <view class="safe-bottom-area"></view>
      </scroll-view>
    </view>

    <!-- 固定添加按钮 -->
    <view class="fixed-action-buttons">
      <view class="action-button" @tap="handleAddRecord(true)">
        <text>批量添加</text>
      </view>
      <view class="action-button primary" @tap="handleAddRecord(false)">
        <text>单笔添加</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useContactStore } from '../../../store/modules/contact';
import { GiftRecord, Contact } from '../../../types/giftbook';

// 定义props
const props = defineProps({
  records: {
    type: Array as () => GiftRecord[],
    default: () => []
  },
  giftBookId: {
    type: String,
    required: true
  }
});

// 定义要向父组件发出的事件
const emit = defineEmits([
  'add-record', 
  'edit-record', 
  'delete-record'
]);

const contactStore = useContactStore();

// 获取联系人列表
const contacts = computed(() => {
  return contactStore.getAllContacts;
});

// 记录展开状态管理
const expandedRecords = ref<Record<string, boolean>>({});

// 排序状态管理
const sortField = ref<string>('time'); // 默认按时间排序
const sortDirection = ref<'asc' | 'desc'>('desc'); // 默认降序排列

// 切换排序字段和方向
const toggleSort = (field: string) => {
  if (sortField.value === field) {
    // 如果已经是当前字段，切换排序方向
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
  } else {
    // 如果是新字段，设置为该字段并使用默认排序方向
    sortField.value = field;
    sortDirection.value = 'asc';
  }
};

// 获取排序后的记录列表
const sortedRecords = computed(() => {
  if (!props.records || props.records.length === 0) return [];
  
  // 创建一个记录列表的副本进行排序
  const sortableRecords = [...props.records];
  
  // 根据排序字段和方向进行排序
  return sortableRecords.sort((a, b) => {
    let compareResult = 0;
    
    // 根据不同的排序字段进行比较
    switch (sortField.value) {
      case 'name':
        // 对联系人姓名进行比较
        const nameA = a.contactName || getContactName(a.contactId) || '';
        const nameB = b.contactName || getContactName(b.contactId) || '';
        compareResult = nameA.localeCompare(nameB, 'zh-CN');
        break;
      
      case 'type':
        // 对记录类型进行比较
        const typeA = a.type || '';
        const typeB = b.type || '';
        compareResult = typeA.localeCompare(typeB);
        break;
      
      case 'amount':
        // 对金额进行比较
        const amountA = a.amount || 0;
        const amountB = b.amount || 0;
        compareResult = amountA - amountB;
        break;
      
      case 'time':
      default:
        // 对时间进行比较
        const timeA = a.createTime || 0;
        const timeB = b.createTime || 0;
        compareResult = timeA - timeB;
        break;
    }
    
    // 根据排序方向调整比较结果
    return sortDirection.value === 'asc' ? compareResult : -compareResult;
  });
});

// 切换记录展开状态
const toggleRecordExpand = (recordId: string) => {
  // 使用解构复制当前状态，避免响应式对象直接修改可能导致的全局影响
  const currentExpanded = { ...expandedRecords.value };
  
  // 只切换当前记录的状态
  currentExpanded[recordId] = !currentExpanded[recordId];
  
  // 更新整个状态对象
  expandedRecords.value = currentExpanded;
};

// 获取记录类型标签
const getRecordTypeLabel = (type: string | undefined) => {
  if (!type) return '请选择类型';
  const typeMap: Record<string, string> = {
    receive: '收礼',
    give: '送礼'
  };
  return typeMap[type] || '-';
};

// 获取联系人姓名
const getContactName = (contactId: string) => {
  if (!contactId) return '未知联系人';
  const contact = contacts.value.find((c: Contact) => c.id === contactId);
  return contact?.name || '未知联系人';
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  return `${String(date.getFullYear())}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化金额，大数字使用简写，整数不显示小数部分
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '0';
  
  // 对大金额进行简化处理
  if (amount >= 100000000) { // 亿
    const value = amount / 100000000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '亿';
  } else if (amount >= 10000) { // 万
    const value = amount / 10000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '万';
  }
  
  // 整数金额不显示小数点后的零
  return Number.isInteger(amount) ? amount.toString() : amount.toFixed(2);
};

// 处理添加记录
const handleAddRecord = (isBatch: boolean) => {
  emit('add-record', isBatch);
};

// 处理编辑记录
const handleEditRecord = (record: GiftRecord) => {
  emit('edit-record', record);
};

// 处理删除记录
const handleDeleteRecord = (record: GiftRecord) => {
  emit('delete-record', record);
};
</script>

<style lang="scss">
.record-list {
  margin-top: var(--spacing-lg);
  background-color: var(--bg-white);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg) var(--spacing-lg) 0 var(--spacing-lg); /* 移除底部padding */
  box-shadow: var(--shadow-sm);
  position: relative;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 300rpx); /* 根据页面实际高度调整 */

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-md);
    flex-shrink: 0;
    padding-bottom: var(--spacing-sm);

    .title {
      font-size: var(--font-lg);
      font-weight: bold;
      color: var(--text-primary);
    }

    .sort-area {
      position: relative;
      
      .sort-hint {
        position: absolute;
        left: 0;
        top: -32rpx;
        background-color: var(--primary-color);
        color: #fff;
        font-size: var(--font-xs);
        padding: 0 var(--spacing-sm);
        border-radius: var(--radius-sm);
        height: 32rpx;
        line-height: 32rpx;
        display: flex;
        align-items: center;
        
        .sort-hint-icon {
          margin-right: var(--spacing-xs);
          font-size: var(--font-xs);
        }
      }
    }
  }

  .record-content {
    flex: 1;
    position: relative;
    overflow: hidden;
  }

  /* 滚动视图样式 */
  .record-scroll-view {
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    padding-bottom: 120rpx; /* 为底部按钮预留空间 */
  }
  
  /* 底部安全区域 */
  .safe-bottom-area {
    height: 120rpx;
    width: 100%;
  }

  /* 排序容器样式 */
  .sort-container {
    display: flex;
    align-items: center;
    gap: var(--spacing-xs);
    
    .sort-item {
      display: flex;
      align-items: center;
      font-size: var(--font-sm);
      color: var(--text-secondary);
      padding: var(--spacing-xs) var(--spacing-sm);
      border-radius: var(--radius-sm);
      border: 1rpx solid var(--border-light);
      background-color: var(--bg-light);
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:active {
        background-color: rgba(0, 0, 0, 0.05);
      }
      
      .sort-icon {
        margin-left: var(--spacing-xs);
        color: var(--primary-color);
        font-weight: bold;
      }
    }
  }

  /* 固定底部添加按钮 */
  .fixed-action-buttons {
    position: absolute;
    right: var(--spacing-lg);
    bottom: var(--spacing-lg);
    display: flex;
    flex-direction: row;
    gap: var(--spacing-md);
    z-index: 100;
    
    .action-button {
      height: 80rpx;
      min-width: 160rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--bg-white);
      color: var(--primary-color);
      font-size: var(--font-md);
      border-radius: 40rpx;
      box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
      padding: 0 var(--spacing-lg);
      transition: all 0.2s ease;
      border: 1rpx solid var(--primary-color);
      
      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }
      
      &.primary {
        background-color: var(--primary-color);
        color: #fff;
      }
    }
  }

  .record-items {
    padding-bottom: var(--spacing-md);
    
    .record-item {
      padding: var(--spacing-md) var(--spacing-lg);
      border-radius: var(--radius-lg);
      margin-bottom: var(--spacing-md);
      box-shadow: var(--shadow-sm);
      transition: all 0.3s ease;
      background-color: var(--bg-light);
      overflow: hidden;
      
      &:active {
        background-color: #f5f5f5;
      }

      &:last-child {
        margin-bottom: 0;
      }
      
      &--receive {
        border-left: 6rpx solid var(--primary-color);
      }
      
      &--give {
        border-left: 6rpx solid var(--danger-color);
      }
      
      &--expanded {
        background-color: var(--bg-white);
        padding-bottom: var(--spacing-lg);
        
        .record-header {
          margin-bottom: var(--spacing-md);
          padding-bottom: var(--spacing-sm);
          border-bottom: 1rpx dashed var(--border-light);
        }
      }

      .record-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;

        .contact-name {
          font-size: 30rpx;
          color: var(--text-primary);
          font-weight: bold;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          flex: 1;
          margin-right: var(--spacing-md);
        }
        
        .header-right {
          display: flex;
          align-items: center;
          gap: var(--spacing-sm);
          flex-shrink: 0;
        }

        .amount {
          font-size: 30rpx;
          font-weight: bold;
          margin-right: var(--spacing-xs);
          
          &.amount-receive {
            color: #67c23a !important;
          }
          
          &.amount-give {
            color: #f56c6c !important;
          }
        }

        .record-type {
          font-size: var(--font-xs);
          padding: 0 var(--spacing-sm);
          border-radius: var(--radius-sm);
          line-height: 32rpx;
          
          &.type-receive {
            color: #67c23a !important;
            background-color: rgba(103, 194, 58, 0.1);
          }
          
          &.type-give {
            color: #f56c6c !important;
            background-color: rgba(245, 108, 108, 0.1);
          }
        }
        
        .expand-arrow {
          font-size: var(--font-xs);
          color: var(--text-hint);
          padding: 0 var(--spacing-xs);
          margin-left: var(--spacing-xs);
          transition: all 0.3s ease;
          width: 30rpx;
          text-align: center;
          
          &.expanded {
            color: var(--primary-color);
            transform: rotate(180deg);
          }
        }
      }
      
      .record-details {
        animation: fadeIn 0.3s ease;
      }
      
      .details-container {
        background-color: var(--bg-light);
        border-radius: var(--radius-md);
        padding: var(--spacing-md);
        margin-bottom: var(--spacing-md);
        border: 1rpx solid var(--border-light);

        .gift-name {
          font-size: var(--font-md);
          color: var(--text-primary);
          margin-bottom: var(--spacing-sm);
          display: flex;
          align-items: center;
          
          .gift-icon {
            margin-right: var(--spacing-sm);
            font-size: var(--font-md);
            flex-shrink: 0;
          }
        }

        .remark {
          font-size: var(--font-sm);
          color: var(--text-secondary);
          display: flex;
          align-items: flex-start;
          
          .remark-icon {
            margin-right: var(--spacing-sm);
            font-size: var(--font-sm);
            flex-shrink: 0;
          }
        }
      }

      .record-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .time {
          font-size: var(--font-sm);
          color: var(--text-hint);
        }

        .actions {
          display: flex;
          align-items: center;
          gap: var(--spacing-md);

          .edit,
          .delete {
            font-size: var(--font-sm);
            padding: 6rpx 14rpx;
            border-radius: var(--radius-sm);
          }

          .edit {
            color: var(--primary-color);
            background-color: var(--background-color);
          }

          .delete {
            color: var(--danger-color);
            background-color: var(--danger-light);
          }
        }
      }
    }
  }

  .empty-state {
    padding: 60rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;

    .empty-icon {
      margin-bottom: var(--spacing-lg);
      
      .emoji {
        font-size: 80rpx;
      }
    }
    
    .empty-title {
      font-size: var(--font-lg);
      color: var(--text-primary);
      font-weight: bold;
      margin-bottom: var(--spacing-sm);
    }
    
    .empty-desc {
      font-size: var(--font-md);
      color: var(--text-hint);
      margin-bottom: var(--spacing-xl);
      padding: 0 40rpx;
    }
  }
}

/* 添加关键帧动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
</style> 